"""入口程序"""
from flask import current_app
from flask import session
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db, redis_store
from info import models

# 创建app对象,传入模式参数
from info.models import User

app = create_app("development")

# 将app对象交给Manager管理
manager = Manager(app)

# 绑定app对象和db对象
Migrate(app, db)

# 自定义数据库迁移指令
manager.add_command("db", MigrateCommand)


# 创建管理员
@manager.option("-n", "-name", dest="name")
@manager.option("-p", "-password", dest="password")
def create_super_user(name, password):
    """创建管理员"""
    if not all([name, password]):
        print("参数不足")
        return

    user = User()
    user.mobile = name
    user.nick_name = name
    user.password = password
    user.is_admin = True

    try:
        db.session.add(user)
        db.session.commit()
        print("创建成功")
    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()

    session["user_id"] = user.id
    session["is_admin"] = True
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile


if __name__ == '__main__':
    # print(app.url_map)
    manager.run()
